import uniqueId from 'lodash.uniqueid'
import eventBus from '@/utils/eventBus'
import { inAnchorPointActive } from '../utils/anchor-point'

let addEdge = null // 待添加的边
let addEdgeSource = null // 待添加的边 - source 信息

eventBus.$on('add-edge', info => {
    addEdgeSource = info
})

// 鼠标 松开时，先执行 node:drop 再执行 dragend
export default {
    getEvents () {
        return {
            drag: 'onDrag',
            dragend: 'onDragEnd',
            'node:drop': 'onNodeDrop'
        }
    },

    onDrag (event) {
        const { graph } = this

        const { x, y } = event

        if (addEdge) {
            graph.updateItem(addEdge, {
                target: { x, y }
            })
        } else {
            const { source, sourceAnchor } = addEdgeSource

            addEdge = graph.addItem('edge', {
                id: uniqueId(),
                source,
                target: { x, y },

                // 该边连入 source 点的第 几 个 anchorPoint
                sourceAnchor,
                // 该边连入 target 点的第 0 个 anchorPoint
                targetAnchor: 0
            })
        }

        graph.setItemState(addEdge, 'add', true)
        graph.paint()
    },

    // 鼠标 松开
    onDragEnd () {
        const { graph } = this

        // 鼠标在画布上松开，未在节点上松开
        if (addEdge) {
            graph.remove(addEdge)
            addEdge = null
        }

        // 清除 锚点 active 样式
        inAnchorPointActive(graph, false)

        graph.setMode('default')
    },

    // 鼠标 在 节点上 松开
    onNodeDrop (event) {
        const { graph } = this

        // 鼠标 在 可连接的 锚点 上 松开
        if (event.target.attrs.isInAnchorPoint) {
            graph.updateItem(addEdge, {
                target: event.item.getModel().id
            })
            graph.setItemState(addEdge, 'add', false)
            graph.paint()
        } else {
            graph.remove(addEdge)
        }

        addEdge = null
    }
}
